package com.ytq.share.algorithm;

import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;
import org.springframework.util.CollectionUtils;

/**
 * @author yuantongqin
 * description:
 * 2020/12/18
 */
public class MyTableComplexKeysShardingAlgorithm implements ComplexKeysShardingAlgorithm<Long> {

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, ComplexKeysShardingValue<Long> shardingValue) {
        Map<String, Collection<Long>> columnMap = shardingValue.getColumnNameAndShardingValuesMap();
        Collection<Long> userIdValue = columnMap.get("user_id");
        Collection<Long> yearNumValue = columnMap.get("year_num");
        if(!CollectionUtils.isEmpty(userIdValue) && !CollectionUtils.isEmpty(yearNumValue)){
            Long userId = userIdValue.stream().findFirst().get();
            Long yearNum = yearNumValue.stream().findFirst().get();
            return availableTargetNames.stream().filter(s -> s.endsWith(yearNum + "_" + (userId % 2)))
                    .collect(Collectors.toList());
        }
        if(!CollectionUtils.isEmpty(yearNumValue) && CollectionUtils.isEmpty(userIdValue)){
            Long yearNum = yearNumValue.stream().findFirst().get();
            return availableTargetNames.stream().filter(s -> s.indexOf(yearNum+"") > 0)
                    .collect(Collectors.toList());
        }
        if(CollectionUtils.isEmpty(yearNumValue) && !CollectionUtils.isEmpty(userIdValue)){
            Long userId = userIdValue.stream().findFirst().get();
            return availableTargetNames.stream().filter(s -> s.endsWith(String.valueOf(userId %2)))
                    .collect(Collectors.toList());
        }
        return availableTargetNames;
    }
}
